package org.bonorsoft.modules.system.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.constant.CacheConstant;
import org.bonorsoft.common.constant.CommonConstant;
import org.bonorsoft.common.dingapi.DingdingUser;
import org.bonorsoft.common.system.api.ISysBaseAPI;
import org.bonorsoft.common.system.util.JwtUtil;
import org.bonorsoft.common.system.vo.LoginDingUser;
import org.bonorsoft.common.util.RedisUtil;
import org.bonorsoft.common.util.ServletUtils;
import org.bonorsoft.common.util.TokenUtils;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.dingding.entity.SysDepart;
import org.bonorsoft.modules.dingding.entity.SysDingUser;
import org.bonorsoft.modules.dingding.service.ISysDepartService;
import org.bonorsoft.modules.dingding.service.ISysDingUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author WilliamYe
 * @since 2020-08-28
 */
@Controller
@Slf4j
public class SysLoginController {

    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private ISysDingUserService sysDingUserService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private RedisUtil redisUtil;
    // 登录地址
    @Value("${william.user.loginUrl}")
    private String loginUrl;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap map)
    {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        map.put("mobile","");
        return "login";
    }

    @GetMapping("/dingding")
    public String dingding(HttpServletRequest request, HttpServletResponse response)
    {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }

        return "dingding";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> login(String mobile){
        Result<JSONObject> result = new Result<JSONObject>();

        //1. 校验手机号码是否有效
        SysDingUser dingUser = sysDingUserService.getUserByMobile(mobile);
        if (oConvertUtils.isEmpty(dingUser)) {
            result.error500("用户不存在于该组织架构，请联系管理员添加！");
            return result;
        }

        //2.检验用户是否激活
        SysDingUser activeUser = sysDingUserService.getUserActiveByMobile(mobile);
        if (oConvertUtils.isEmpty(activeUser)) {
            result.error500("账号未激活，请进行激活操作！");
            return result;
        }

        //用户登录信息
        userInfo(activeUser, result);
        sysBaseAPI.addLog(activeUser.getUserid(), CommonConstant.LOG_TYPE_1, CommonConstant.OPERATE_TYPE_7);

        return result;
    }

    @RequestMapping(value = "/dingding", method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> dingding(String code){
        Result<JSONObject> result = new Result<JSONObject>();
        //对接钉钉，获取用户userid
        String user_id = DingdingUser.getuserId(code);
        String userInfo = DingdingUser.getUser(user_id);
        SysDingUser user = JSONUtil.toBean(userInfo, SysDingUser.class);
        SysDingUser dingUser = sysDingUserService.getUserByMobile(user.getMobile());
        //1. 校验用户是否存在
        if (oConvertUtils.isEmpty(dingUser)) {
            result.error500("用户不存在于该组织架构，请联系管理员添加！");
            return result;
        }

        //2.检验用户是否激活
        if (dingUser.getActive() == 0) {
            result.error500("账号未激活，请进行激活操作！");
            return result;
        }

        //用户登录信息
        userInfo(dingUser, result);
        sysBaseAPI.addLog(dingUser.getUserid(), CommonConstant.LOG_TYPE_1, CommonConstant.OPERATE_TYPE_7);

        return result;
    }


    /**
     * 用户信息
     *
     * @param sysUser
     * @param result
     * @return
     */
    private Result<JSONObject> userInfo(SysDingUser sysUser, Result<JSONObject> result) {
        String mobile = sysUser.getMobile();
        String userId = sysUser.getUserid();
        // 生成token
        String token = JwtUtil.sign(userId, mobile);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);
        // 获取用户部门信息
        JSONObject obj = new JSONObject();
        List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getUserid());
        obj.put("departs", departs);
        if (departs == null || departs.size() == 0) {
            obj.put("multi_depart", 0);
        } else if (departs.size() == 1) {
            sysDingUserService.updateUserDepart(userId, departs.get(0).getDeptId());
            obj.put("multi_depart", 1);
        } else {
            obj.put("multi_depart", 2);
        }
        obj.put("token", token);
        obj.put("userInfo", sysUser);
        result.setResult(obj);
        result.success("登录成功");
        return result;
    }


    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
        //用户退出逻辑
        String token = TokenUtils.getTokenByRequest(request);
        if(oConvertUtils.isEmpty(token)) {
            return "退出登录失败！";
        }
        String userId = JwtUtil.getUserId(token);
        LoginDingUser dingUser = sysBaseAPI.getUserById(userId);
        if(dingUser!=null) {
            sysBaseAPI.addLog(dingUser.getUserid(), CommonConstant.LOG_TYPE_1, CommonConstant.OPERATE_TYPE_8);
            log.info(" 用户名:  "+dingUser.getName()+",退出成功！ ");
            //清空用户登录Token缓存
            redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
            //清空用户登录Shiro权限缓存
            redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + dingUser.getUserid());
            //清空用户的缓存信息（包括部门信息），例如sys:cache:user::<username>
            redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, dingUser.getUserid()));
            //调用shiro的logout
            SecurityUtils.getSubject().logout();
            map.put("mobile",dingUser.getMobile());
            return loginUrl;
        }else {
            return "Token无效!";
        }
    }


    /**
     * 选择当前登陆部门
     * @param map
     * @return
     */
    @GetMapping("/selectDepart")
    public String selectDepart(@RequestParam(name="userId",required=true) String userId, ModelMap map)
    {
        LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();
        List<SysDepart> departs = sysDepartService.queryUserDeparts(userId);
        map.put("userId",userId);
        map.put("departs",departs);
        map.put("currentDeptId",user.getDeptId());
        return "system/user/dept/selectDepart";
    }

    @RequestMapping(value = "/selectDepart", method = RequestMethod.POST)
    @ResponseBody
    @CacheEvict(cacheNames= CacheConstant.SYS_USERS_CACHE, key="#userId")
    public Result<?> selectDepart(String userId, Long deptId){
        sysDingUserService.updateUserDepart(userId, deptId);
        sysBaseAPI.setLoginDingUser(sysBaseAPI.getUserById(userId));
        return Result.ok("部门选择成功");
    }


}
